/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.ensisa.sunspot.actor.writer.strategy;

import fr.ensisa.sunspot.actor.writer.media.IMedia;
import fr.ensisa.sunspot.event.IEvent;

/**
 *
 * @author michel
 */
public class BufferedWriter extends AbstractWriteStrategy {

    private IEvent record [];
    private int count = 0;

    public BufferedWriter (int size, IMedia media) {
        super (media);
        this.record = new IEvent [size];
        this.count = 0;
    }

    public void setActivated (boolean activated) {
        if (activated) {
            count = 0;
        }
        super.setActivated(activated);
    }

    public void write (long timeStamp, IEvent incomingEvent) {
        if (! isActivated()) return;
        if (incomingEvent == null) return;
        if (record[0] != null && incomingEvent.getTimeStamp() != record[0].getTimeStamp()) {
            doPrint (timeStamp, incomingEvent);
        }
        if (count < record.length) {
            record[count++] = incomingEvent.clone();
        }
        if (count == record.length) {
            doPrint (timeStamp, incomingEvent);
        }
    }

    private void doPrint (long timeStamp, IEvent incomingEvent) {
        getMedia().writeHeader (timeStamp, record[0]);
        for (int i=0; i < record.length;++i) {
            IEvent event = record[i];
            if (event != null) {
                getMedia().writeEvent (timeStamp, event);
            }
            event = null;
            record[i] = null;
        }
        count=0;
        getMedia().writeTrailer (timeStamp, record[0]);
    }

}
